package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    // =======以下服务是服务降级
    /**
     * hystrix正常访问
     * @param id
     * @return
     */
    public String paymentInfoOk( Integer id ) {
        return "线程池：" + Thread.currentThread().getName() +" paymentInfoOk,id:"+id + "\t" + "哈哈 正确了";
    }

    /**
     * hystrix 访问超时
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfoTimeOuTHandler", commandProperties = { // 设置超时时间
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    }) // 服务降级
    public String paymentInfoTimeOuT( Integer id ) {

        int timeNumber = 3;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // int age = 10 / 0;
        return "线程池：" + Thread.currentThread().getName() +" paymentInfoTimeOuT,id:"+id + "\t" + "哈哈 正确了，耗时三秒钟";
    }

    /**
     * 服务降级所返回的一个可预期的参数
     * @return
     */
    public String paymentInfoTimeOuTHandler( Integer id ){
        return "线程池：" + Thread.currentThread().getName() +" ,paymentInfoTimeOuTHandler,系统繁忙或则运行报错,id:" + id + "\t" + "不好意思，超时了";
    }







    //======= 以下代码都是服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {      // 服务降级方法
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),                      // 是否开启断路器

            // x次下失败率达到**下就短路，在***秒后，尝试半开放
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),        // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),      // 失败率到达多少后跳闸
    })
    public String paymentCircuitBreader( @PathVariable("id") Integer id ) {

        if ( id < 0 ) {
            throw new RuntimeException("**************id不能为负数");
        }

        // 获取一个通用的uuid
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t 调用成功，当前流水号：" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback( @PathVariable("id") Integer id ) {
        return "id不能为负数，请稍后再试！！！我是服务降级~~~~id="+id;
    }
}
